import { createApp, h } from 'vue'
import ConfirmDialog from './vConfirm.vue'

export const vConfirm = (options) => {
    return new Promise((resolve, reject) => {
        const container = document.createElement('div')
        document.body.appendChild(container)

        const tempApp = createApp({
            render() {
                return h(ConfirmDialog, {
                    ...options,
                    onConfirm: (value) => resolve(value),
                    onCancel: () => reject(new Error('confirm canceled')),
                    onClosed: () => {
                        tempApp.unmount()
                        container.remove()
                    }
                })
            }
        })

        tempApp.mount(container)
    })
}

export default {
    install(app) {
        app.config.globalProperties.$vConfirm = vConfirm
        app.component('ConfirmDialog', ConfirmDialog)
    }
}